package com.zhuozhou.jdyc.main.main.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhuozhou.jdyc.R;
import com.zhuozhou.jdyc.api.UserAccountHelper;
import com.zhuozhou.jdyc.base.BaseFragment;
import com.zhuozhou.jdyc.bean.BannerBean;
import com.zhuozhou.jdyc.databinding.FragmengBarterBinding;
import com.zhuozhou.jdyc.main.goods.activity.GoodsDetailActivity;
import com.zhuozhou.jdyc.main.main.activity.GoodsClassifyActivity;
import com.zhuozhou.jdyc.main.main.activity.MainActivity;
import com.zhuozhou.jdyc.main.main.adapter.BarterImageAdapter;
import com.zhuozhou.jdyc.main.main.adapter.BarterShopAdapter;
import com.zhuozhou.jdyc.main.main.adapter.IndexMenuAdapter;
import com.zhuozhou.jdyc.main.main.bean.BasicsTypeBean;
import com.zhuozhou.jdyc.main.main.bean.MenuItemBean;
import com.zhuozhou.jdyc.main.main.viewmodel.MainViewModel;
import com.zhuozhou.jdyc.wight.recyclerview.FullyGridLayoutManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Create by Once_ChuXy on 2021/8/19
 * Describe:积分
 */
public class BarterFragment extends BaseFragment<MainViewModel, FragmengBarterBinding> implements IndexMenuAdapter.OnItemClickListener,
        BarterShopAdapter.OnShopItemClickListener, BarterImageAdapter.OnImageItemClickListener, OnLoadMoreListener {
    private IndexMenuAdapter indexMenuAdapter;
    private BarterShopAdapter barterShopAdapter;
    private BarterImageAdapter barterImageAdapter;
    protected SmartRefreshLayout refreshLayout;
    private int page = 1;

    @Override
    public void onResume() {
        super.onResume();
        page = 1;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragmeng_barter;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            ((MainActivity) getActivity()).setThemeBarAndToolBarColor(R.color.themeColor);
        }
        refreshLayout = view.findViewById(R.id.smartFreshLayout);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setEnableRefresh(false);
        binding.searchEdit.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.searchEdit.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                try {
                    Intent in = new Intent(getActivity(), GoodsClassifyActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("searchEdit", v.getText().toString());
                    bundle.putInt("type", 3);
                    in.putExtras(bundle);
                    startActivity(in);
                    // 当按了搜索之后关闭软键盘
                    ((InputMethodManager) binding.searchEdit.getContext().getSystemService(
                            Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                            getActivity().getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return false;
        });
        mViewModel.basicsTypeMutableLiveDataIntegral.observe(this, basicsTypeBean -> {
            List<MenuItemBean> list = new ArrayList<>();
            for (BasicsTypeBean.ArrayBean.TypeBean type : basicsTypeBean.getArray().getType()) {
                list.add(new MenuItemBean(type.getImage(), type.getName(), type.getId() + "", GoodsClassifyActivity.class, 30000));
            }
            indexMenuAdapter = new IndexMenuAdapter(getActivity());
            indexMenuAdapter.setList(list);
            indexMenuAdapter.setTextColor(R.color.white);
            indexMenuAdapter.setViewWidth(binding.mRecyclerViewMenu.getWidth() / 5);
            indexMenuAdapter.setOnItemClickListener(this);
            binding.mRecyclerViewMenu.setAdapter(indexMenuAdapter);
            binding.mRecyclerViewMenu.setLayoutManager(new FullyGridLayoutManager(getActivity(), 2, LinearLayoutManager.HORIZONTAL, false) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            List<BannerBean> bannerList = new ArrayList<>();
            for (BasicsTypeBean.ArrayBean.BannerBean type : basicsTypeBean.getArray().getBanner()) {
                bannerList.add(new BannerBean(type.getImage(), type.getTitle(), type.getContent()));
            }
            binding.indexBannerPicture.setRoundDots(R.drawable.rounded_theme_rect, R.drawable.rounded_default_bg_rect);
            binding.indexBannerPicture.initView(bannerList);
            if (page > 1 && barterShopAdapter != null) {
                if (basicsTypeBean.getArray().getCommodity().size() == 0) {
                    refreshLayout.finishRefreshWithNoMoreData();
                    binding.tvNoData.setVisibility(View.VISIBLE);
                } else {
                    barterShopAdapter.addAll(basicsTypeBean.getArray().getCommodity());
                    barterShopAdapter.notifyDataSetChanged();
                    refreshLayout.finishLoadMore();
                }
            } else {
                barterShopAdapter = new BarterShopAdapter(getActivity());
                barterShopAdapter.setList(basicsTypeBean.getArray().getCommodity());
                barterShopAdapter.setOnShopItemClickListener(this);
                binding.mRecyclerViewShop.setAdapter(barterShopAdapter);
                binding.mRecyclerViewShop.setLayoutManager(new FullyGridLayoutManager(getActivity(), 2) {
                    @Override
                    public boolean canScrollVertically() {
                        return false;
                    }
                });
            }
        });

        mViewModel.BasicsYiHuoStopMutableLiveData.observe(this, v -> {
            if (v.size() == 0) {
                binding.rlTitle.setVisibility(View.GONE);
            } else {
                binding.rlTitle.setVisibility(View.VISIBLE);
                barterImageAdapter = new BarterImageAdapter(getActivity());
                barterImageAdapter.setList(v);
                barterImageAdapter.setOnImageItemClickListener(this);
                binding.mRecyclerViewRecommend.setAdapter(barterImageAdapter);
                binding.mRecyclerViewRecommend.setLayoutManager(new FullyGridLayoutManager(getActivity(), 3) {
                    @Override
                    public boolean canScrollVertically() {
                        return false;
                    }
                });
            }
        });

        binding.mScrollView.setOnScrollChangeListener((v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            if (scrollY >= (binding.mScrollView.getHeight() / 4)) {
                binding.imageTop.setVisibility(View.VISIBLE);
            }
            if (scrollY <= (binding.mScrollView.getHeight() / 4)) {
                binding.imageTop.setVisibility(View.GONE);
            }
        });

        binding.imageTop.setOnClickListener(v -> {
            binding.mScrollView.fullScroll(View.FOCUS_UP);
        });

    }

    @Override
    public void initData(Bundle bundle) {
        mViewModel.getBasicsTypeIntegral(UserAccountHelper.getNewCity(), page, 3);
        mViewModel.getBasicsYiHuoStop(UserAccountHelper.getNewCity());

    }

    @Override
    public void onItemClick(View view, int position) {
        Intent intent = new Intent(getActivity(), indexMenuAdapter.getList().get(position).getClx());
        Bundle bundle = new Bundle();
        bundle.putInt("id", Integer.parseInt(indexMenuAdapter.getList().get(position).getTag()));
        bundle.putString("name", indexMenuAdapter.getList().get(position).getImageName());
        bundle.putInt("type", 3);
        intent.putExtras(bundle);
        startActivityForResult(intent, indexMenuAdapter.getList().get(position).getRequestCode());
    }

    @Override
    public void onShopItemClick(View view, int position) {
        Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("id", barterShopAdapter.getList().get(position).getId() + "");
        bundle.putInt("type", 3);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void onImageItemClick(View view, int position) {
        Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("id", barterImageAdapter.getList().get(position).getId() + "");
        bundle.putInt("type", 3);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        mViewModel.getBasicsTypeIntegral(UserAccountHelper.getNewCity(), page, 3);
    }
}
